package com.inwavetech.os.util;

import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by jgskin on 1/22/14.
 */
public class Request {

    private DefaultHttpClient client;

    public Request() {
        this.client = new DefaultHttpClient();
    }

    public SimpleResponse post(String url, List<BasicNameValuePair> params) {
        HttpPost method = new HttpPost(url);

        try {
            method.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            Log.e(Request.class.getName(), "wrongly configured post params");
        }

        return fetchResponse(configureMethod(method));
    }

    public SimpleResponse get(String url) {
        HttpGet method = new HttpGet(url);

        return fetchResponse(configureMethod(method));
    }

    protected HttpRequestBase configureMethod(HttpRequestBase method) {
        return method;
    }

    protected SimpleResponse fetchResponse(HttpRequestBase method) {
        // init
        SimpleResponse simpleResponse = null;

        try {
            // try to fetch the response
            HttpResponse response = client.execute(method);

            // response received. build the simple response
            simpleResponse = new SimpleResponse();
            simpleResponse.code = response.getStatusLine().getStatusCode();

            // try to parse the server response body
            try {
                simpleResponse.body = EntityUtils.toString(response.getEntity());
            } catch (IOException e) {
                // no luck
                Log.e(this.getClass().getName(), "Unable to parse server response");
            }

        } catch (IOException e) {
            // no luck
            Log.e(Request.class.getName(), "the host could not be reached");
        }

        return simpleResponse;
    }
}
